package com.biz.primus.ms.depot.dao.redis;

import com.biz.primus.base.redis.CrudRedisDao;
import com.biz.primus.base.redis.util.RedisUtil;
import com.biz.primus.ms.depot.dao.ro.FreightTemplateRo;
import org.springframework.stereotype.Repository;

/**
 * FreightTemplateRedisDao
 *
 * @author JKLiues
 * @date 2017年11月03日
 */
@Repository
public class FreightTemplateRedisDao extends CrudRedisDao<FreightTemplateRo, Long> {


    public FreightTemplateRo findByCode(String code) {
        String freightCode = getCode2IdMappingKey(code);
        byte[] bytes = get(freightCode);
        Long aLong = RedisUtil.byteArrayToLong(bytes);
        return super.findOne(aLong);
    }

    @Override
    public void save(FreightTemplateRo ro) {
        super.save(ro);
        this.doMapping(ro);
    }

    @Override
    public void save(Iterable<FreightTemplateRo> ros) {
        super.save(ros);
        ros.forEach(this::doMapping);
    }

    public void doMapping(FreightTemplateRo ro) {
        String code2IdMappingKey = this.getCode2IdMappingKey(ro.getFreightCode());
        super.set(code2IdMappingKey, RedisUtil.toByteArray(ro.getId()));
    }

    private String getCode2IdMappingKey(String code) {
        return getKeyByParams("code", code);
    }

}